import config from '../config.js'
const request = (obj) => {
	obj.url = obj.url || ''; // 请求路径
	obj.method = obj.method || 'GET'; //请求方式
	obj.data = obj.data || {}; //请求携带的数据
	obj.header = obj.header || 'application/json'; //请求头信息 content-type
	obj.loading = obj.loading === false ? false : true; //是否显示请求加载中
	obj.requestTime = obj.requestTime || 500; //多久时间内完成网络请求，则不显示提示框
	let loadingStatus = true;
	//返回Promise对象
	return new Promise((resolve, reject) => {
		let BASE_URL = config.baseUrl

		const header = {
			...obj.header
		}
		// uni.showLoading()
		uni.request({
			url: obj.url,
			method: obj.method,
			header: header,
			...obj.option,
			data: {
				...obj.data,
			},
			success: res => {
				console.log(res, 'ssss');
				resolve(res.data);

			},
			fail: err => {
				uni.showToast({
					duration: 3000,
					title: err,
					icon: 'none'
				})
				reject(err);

			},
			complete: () => {
				// uni.hideLoading();
				uni.stopPullDownRefresh()
				loadingStatus = false;
			}
		})
	});
}

const post = (url, data, header, option={}) => {
	let res = request({
		url,
		data,
		loading: true,
		method: 'POST',
		header: header || {
			'Content-Type': 'application/x-www-form-urlencoded'
		},
		option: option
	})
	return res
}

const get = (url, data) => {
	let res = request({
		url,
		data,
		loading: true,
		header: {
			'Content-Type': 'application/json'
		},
		method: 'GET',
		option: {}
	})
	return res
}
/**
 * 
 * 上传文件
 * @fileList {array} 需要上传的文件列表 
 * @name {string} 后端接收文件字段
 * @fileType {string} 上传文件类型 image/video
 * @option 
 */
const uploadFiles = (fileList, httpUrl, option = {}, name = 'file') => {
	let request = ""

	return new Promise((reslove, reject) => {
		uni.showLoading({
			title: '上传中...',
		})
		uni.uploadFile({
			url: config.baseUrl + (httpUrl || "/mobile/my/upload.html"), //上传至服务器接口
			filePath: fileList, //上传文件
			name: 'file', //服务器接收字段
			header: {
				'Content-Type': 'multipart/form-data',
			},
			formData: {
				...option,
				openid: uni.getStorageSync('openid')
			},
			success: (res) => {
				console.log(res, "success");
				reslove(JSON.parse(res.data))
			},
			fail: (res) => {
				console.log(res, 'aa');
				uni.showToast({
					title: res.data,
					duration: 3000,
					icon: 'none'
				})
				reject(res.data)
			},
			complete() {
				uni.hideLoading()
			}
		})
	})
}
export {
	request,
	get,
	post,
	uploadFiles
};